import { CordModel, ThingSizeModel } from "./model";

export class Tool {

    public static hasCollision(blockArr: CordModel[], wallSize: number, size: ThingSizeModel): { xReach: boolean, yReach: boolean, item?: CordModel } {
        let xReach = false;
        let yReach = false;

        let midX = (size.x1 + size.x2) / 2;
        let midY = (size.y1 + size.y2) / 2;

        for (let item of blockArr) {
            if (!xReach) {
                let innerXReach = false;
                let innerYReach = false;
                if (item.x * wallSize < size.x1 && item.x * wallSize + wallSize > size.x1) {
                    innerXReach = true;
                }
                else if (item.x * wallSize < size.x2 && item.x * wallSize + wallSize > size.x2) {
                    innerXReach = true;
                }

                if (item.y * wallSize < midY && item.y * wallSize + wallSize > midY) {
                    innerYReach = true;
                }

                if (innerXReach && innerYReach) {
                    xReach = true;
                }
            }

            if (!yReach) {
                let innerXReach = false;
                let innerYReach = false;
                if (item.x * wallSize < midX && item.x * wallSize + wallSize > midX) {
                    innerXReach = true;
                }

                if (item.y * wallSize < size.y1 && item.y * wallSize + wallSize > size.y1) {
                    innerYReach = true;
                }
                else if (item.y * wallSize < size.y2 && item.y * wallSize + wallSize > size.y2) {
                    innerYReach = true;
                }

                if (innerXReach && innerYReach) {
                    yReach = true;
                }
            }

            if (xReach || yReach) {
                return { xReach, yReach, item }
            }
        }
        return { xReach, yReach }
    }

    /**
     * 将相对url转换成当前js文件同级的绝对文件
     * @param url
     * @returns
     */
    public static getAbsolutePath(url: string) {
        let scripts = document.getElementsByTagName("script");

        let src = '';

        for (let i = 0; i < scripts.length; i++) {
            let curSrc = scripts[i].src;
            if (curSrc.indexOf('ping-pang-game.js') >= 0) {
                src = curSrc
                break;
            }
        }

        return src.replace('ping-pang-game.js', url);
    }
}